<script setup>
import { onMounted, ref, onUnmounted, nextTick } from 'vue';

import 'cesium/Build/CesiumUnminified/Widgets/widgets.css';
import { addCunzhenPoint, addGeojsonArea, startMouseMove } from '../../utils/map';
import {
	TileMapServiceImageryProvider,
	Viewer,
	buildModuleUrl,
	Cartesian3,
	CustomDataSource,
	Math,
	ScreenSpaceEventType,
	ScreenSpaceEventHandler,
	SceneTransforms,
	Color,
	GeoJsonDataSource,
	defined,
	Entity,
	ImageryLayer
} from 'cesium';
import { getHomeData } from '../../pages/home/service';
import { useRouter } from 'vue-router';

const router = useRouter();
const viewerDivRef = ref();
const baseLayer1 = new ImageryLayer.fromProviderAsync(
	TileMapServiceImageryProvider.fromUrl(buildModuleUrl('Assets/Textures/NaturalEarthII'), {})
);
let timeID = null;
onMounted(() => {
	nextTick(() => {
		let viewer = new Viewer(viewerDivRef.value, {
			orderIndependentTranslucency: false,
			contextOptions: {
				webgl: {
					alpha: true
				}
			},
			// imageryProvider: new TileMapServiceImageryProvider({
			// 	url: buildModuleUrl('Assets/Textures/NaturalEarthII')
			// }),
			baseLayer: baseLayer1,
			homeButton: false,
			// baseLayer: false,
			fullscreenButton: false,
			sceneModePicker: false, //是否显示场景按钮
			baseLayerPicker: false, //是否显示图层选择控件
			navigationHelpButton: false, //导航帮助按钮
			selectionIndicator: false, //鼠标选择指示器
			infoBox: false, //信息提示框
			animation: false, //是否创建动画小器件，左下角仪表
			timeline: false, //是否显示时间线控件
			geocoder: false, //是否显示地名查找控件
			shouldAnimate: false
		});
		window.Viewer = viewer;
		let selectedGeojsonDataSources = new CustomDataSource('selectedGeojsonDataSources');

		window.selectedGeojsonDataSources = selectedGeojsonDataSources;

		// 创建一个新的 GeoJSON 数据源
		let geoJsonDataSource = new GeoJsonDataSource('geoJsonDataSource');

		window.Viewer.scene.primitives.add(geoJsonDataSource);
		window.geoJsonDataSource = geoJsonDataSource;

		let singelGeoJsonDataSource = new GeoJsonDataSource('singelGeoJsonDataSource');

		window.Viewer.scene.primitives.add(singelGeoJsonDataSource);
		window.singelGeoJsonDataSource = singelGeoJsonDataSource;

		// 地球球体透明
		// viewer.scene.globe.show = false; //不显示地球，这条和地球透明度选一个就可以
		//  viewer.scene.globe.showGroundAtmosphere = false;
		window.Viewer.scene.globe.baseColor = new Color(0.0, 0.0, 0.0, 0.0);
		// viewer.scene.globe.translucency.enabled = true;
		//  viewer.scene.globe.undergroundColor = undefined;
		window.Viewer.scene.sun.show = false; //在Cesium1.6(不确定)之后的版本会显示太阳和月亮，不关闭会影响展示
		window.Viewer.scene.moon.show = false;
		window.Viewer.scene.skyBox.show = false; //关闭天空盒，否则会显示天空颜色
		window.Viewer._cesiumWidget._creditContainer.style.display = 'none';
		//禁止角度倾斜
		window.Viewer.scene.screenSpaceCameraController.enableTilt = false;
		// viewer.scene.screenSpaceCameraController.enableTranslate = false;

		//禁止地球旋转 拖动
		//   viewer.scene.screenSpaceCameraController.enableRotate = false;
		//显示刷新率和帧率
		window.Viewer.scene.debugShowFramesPerSecond = true;

		// //禁止地球缩放
		//   viewer.scene.screenSpaceCameraController.enableZoom = false;

		// viewer.trackedEntity = undefined;
		window.Viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

		// viewer.scene.screenSpaceCameraController.enableZoom = false;
		window.Viewer.camera.setView({
			destination: Cartesian3.fromDegrees(110.3862821, 38.8426176, 200000.0), // 设置位置
			orientation: {
				heading: Math.toRadians(20.0), // 方向
				pitch: Math.toRadians(-90.0), // 倾斜角度
				roll: 0
			}
		});

		let position = Cartesian3.fromDegrees(110.3858649, 38.8445026); // 例如：中心坐标

		// 计算屏幕坐标
		let screenCoordinates = SceneTransforms.wgs84ToWindowCoordinates(window.Viewer.scene, position);

		window.geoJsonDataSource.show = true;
		window.singelGeoJsonDataSource.show = false;
		window.Viewer.dataSources.removeAll();
		window.Viewer.dataSources.add(selectedGeojsonDataSources);

		window.handler = new ScreenSpaceEventHandler(viewer.scene.canvas);
		window.handler.setInputAction(movement => {
			console.log('双击点击时间');
			// // 假设要判断的坐标点为 Cartesian3 类型的 position
			let position = Cartesian3.fromDegrees(110.3858649, 38.8445026); // 例如：中心坐标

			// 计算屏幕坐标
			let screenCoordinates = SceneTransforms.wgs84ToWindowCoordinates(window.Viewer.scene, position);

			// 判断是否在屏幕范围内
			if (
				screenCoordinates.x >= 0 &&
				screenCoordinates.x <= window.Viewer.container.clientWidth &&
				screenCoordinates.y >= 0 &&
				screenCoordinates.y <= window.Viewer.container.clientHeight
			) {
				// 在当前屏幕视角范围内
			} else {
				// 不在当前屏幕视角范围内

				window.Viewer.camera.setView({
					destination: Cartesian3.fromDegrees(110.3464048, 38.8810109, 3500.0), // 设置位置
					orientation: {
						heading: Math.toRadians(20.0), // 方向
						pitch: Math.toRadians(-90.0), // 倾斜角度
						roll: 0
					}
				});
			}
			//双击事件 取消 高亮实体

			//设置 标记

			// 点击获取鼠标位置

			let pickedObject = window.Viewer.scene.pick(movement.position);
			// 判断是否有实体被选中 直接使用pickedObject.id.polygon
			if (defined(pickedObject) && pickedObject.id instanceof Entity && pickedObject.id.polygon) {
				console.log('pickedObject', pickedObject.id, pickedObject.id.name);

				if (window.geoJsonDataSource.show && pickedObject.id.name != undefined) {
					window.geoJsonDataSource.show = false;
					window.singelGeoJsonDataSource.show = true;
					window.Viewer.dataSources.removeAll();

					addGeojsonArea(
						'/street/' + pickedObject.id.name + '.geojson',
						Color.fromCssColorString('rgba(12,255,3,0.1)'),
						window.singelGeoJsonDataSource,
						1
					).then(id => {
						getHomeData({ id: id }).then(res => {
							res.dzbPoi.forEach(item => {
								addCunzhenPoint(item.name, item.level, item.lon, item.lat, item.cunzhenId);
							});
						});
					});
				}
			}
		}, ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
		window.handler.setInputAction(function (click) {
			console.log('单击点击事件');
			let pick = window.Viewer.scene.pick(click.position);
			if (pick.id && pick.id.poiId) {
				router.push({
					path: '/partyBuilding',
					query: {
						id: pick.id.poiId,
						name: pick.id.name
					}
				});
			}
		}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
		startMouseMove();
		addGeojsonArea('/sms.geojson', Color.fromCssColorString('rgba(12,255,3,0.1)'), window.geoJsonDataSource);

		let button = document.getElementById('fhsy');

		button.addEventListener('click', () => {
			window.singelGeoJsonDataSource.show = false;
			window.Viewer.dataSources.removeAll();
			window.Viewer.dataSources.add(selectedGeojsonDataSources);
			window.geoJsonDataSource.show = true;
			window.Viewer.entities.removeAll();
			addGeojsonArea('/sms.geojson', Color.fromCssColorString('rgba(12,255,3,0.1)'), window.geoJsonDataSource, 0);
			window.Viewer.camera.setView({
				destination: Cartesian3.fromDegrees(110.3862821, 38.8426176, 200000.0), // 设置位置
				orientation: {
					heading: Math.toRadians(20.0), // 方向
					pitch: Math.toRadians(-90.0), // 倾斜角度
					roll: 0
				}
			});
		});

		window.Viewer.scene.screenSpaceCameraController.minimumZoomDistance = 2000;
		window.Viewer.scene.screenSpaceCameraController.maximumZoomDistance = 220000;

		//判断是否支持图像渲染像素化处理
		window.Viewer.resolutionScale = window.devicePixelRatio;

		window.Viewer.scene.fxaa = true;
		window.Viewer.scene.postProcessStages.fxaa.enabled = true;
	});

	// 鼠标移动事件handlClick.setInputAction(function (event) {console.log("123")}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);// 鼠标右键点击事件handlClick.setInputAction(function (event) {console.log("456")}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);/* * cesium 获取不同对象的方法* scene.pick 返回包含窗口位置基元的对象* scene.drillPick 返回给定窗口位置所有对象的列表* Globe.pick 返回的是给定光线和地形的交点*/});return {};
});
onUnmounted(() => {
	timeID && clearInterval(timeID);
});
</script>

<template>
	<div id="cesium-viewer" ref="viewerDivRef">
		<div style="position: absolute; float: left; z-index: 1000000">
			<button id="fhsy">复位</button>
		</div>
	</div>
</template>

<style scoped>
#cesium-viewer {
	width: 100%;
	height: 100%;
}

.sy {
	width: 100%;
	height: 100%;
	position: absolute;
	background-image: url('../src/assets/images/bj.png');
	background-size: cover;
}
</style>
